<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" round size="small" @click="dialogFormVisible = true;isType=true">添加角色</el-button>
      <el-table :data="list">
        <el-table-column prop="name" align="center" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.tag" v-model.trim="row.cache.name" size="small" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="启用">
          <template v-slot="{row}">
            <el-switch
              v-model="row.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              @change="btnSwitch($event,row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.tag" v-model.trim="row.cache.description" type="textarea" autosize />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="row.tag">
              <!-- 编辑状态 -->
              <el-button plain size="small" type="success" @click="editOK(row)">确定</el-button>
              <el-button plain size="small" type="danger" @click="editCancel(row)">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button type="text" @click="btnPrivileges(row.id)">分配权限</el-button>
              <el-button type="text" @click="updataRoleList(row)">编辑</el-button>

              <template>
                <el-popconfirm
                  title="确定删除吗？"
                >
                  <el-button slot="reference" style="margin-left: 10px" type="text" @click="delRoleList(row.id)">删除</el-button>
                </el-popconfirm>
              </template>

            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="dibu">
        <el-pagination
          :total="pageList.total"
          :current-page="pageList.page"
          :page-size="pageList.pagesize"
          layout="prev, pager, next"
          @current-change="roleBtnPage"
        />
      </el-row>
    </div>
    <!-- 新增弹层 -->
    <el-dialog :title="'新增角色'" :visible.sync="dialogFormVisible" width="500px" @close="btnCancel">
      <el-form ref="roleForm" :model="formValue" label-width="120px" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formValue.name" />
        </el-form-item>
        <el-form-item label="是否启用">
          <!-- 想要重置表单，要加上props属性 -->
          <el-switch
            v-model="formValue.state"
            prop="state"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formValue.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="btnOK">确 定</el-button>
          <el-button @click="btnCancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色弹层 -->
    <el-dialog :title="'分配权限'" :visible="privileges" width="500px" @close="privileges=false">
      <!-- 树形权限分配 -->
      <el-tree
        ref="premTree"
        node-key="id"
        :default-checked-keys="userPermIds"
        :data="privilegesList"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
      />
      <el-row slot="footer" type="flex" justify="center">

        <el-button size="small" type="primary" @click="sendIsOk">确定</el-button>
        <el-button size="small" @click="privileges=false">取消</el-button>

      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, setNewRole, updateLonely, delLonely, getPermissionList, getUserById, putAssignPrem } from '@/api/role'
import { Message } from 'element-ui'
import { transListToTreeData } from '@/utils/auth'
// 路由配置信息
import router from '@/router'
import store from '@/store'
import { asyncRoutes } from '@/router'
export default {
    name: 'Role',
    data() {
        return {
            list: [],
            // 分页
            pageList: {
                page: 1,
                pagesize: 10,
                total: 0 // 总条数
            },
            // 新增弹层
            formValue: {
                name: '',
                state: 0,
                description: ''
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    }
                ],
                description: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    }
                ]
            },
            dialogFormVisible: false,
            // 分配权限的弹框
            privileges: false,
            // 弹出层权限列表
            privilegesList: [],
            // 权限受控列表
            userPermIds: [],
            user: null
        }
    },
    async created() {
        this.getPageList()

        // for (let i = 0; i < 10; i++) {
        //     await setNewRole({
        //         name: Math.floor(Math.random() * 100000) + 1,
        //         state: 0,
        //         description: i + 1
        //     })
        // }

        // 仝健健边鸿煊海南蕾好明泽蓟清遥邬虎仔随玉明月
        // 阿齐申屠小葛边浅慕宜娟儿随妍婕父小竹公羊珏华
        // 父禹浩通幻柏澹子宸呼夏瑶闾林林贺旋汎薛润舟公羊云斓是伟刚澹彦辉志黛沫通婵公羊
        // 梓轩通风玮庞音申屠高阳其微顾志承允轩小森斓杨凯公羊玉米班浩奇盘正成轩振儿薛仪明申屠建瑜
        // 贯丘茜彦通英睿仝玮桦庞茉薛蕊蕊文恒文申双冰媛浸溪随芸颖贯丘玖兮沙彦屏澹小葶尚凡林刚炎昊
        // 东里玉麟通扑萤卫玥华闾潇诺倪绍晖庞晨濡尚方妏刚熠煜沙凡蕾草梦莲东里小陈仝心远刚小雅东里
        // 悠兰居永淳公羊祺林贺艺菡仝芯于其叶青月茜玉志妙佳雨秉月边菜菜狐甜汐边旭卉
    },
    methods: {
        // 确认修改
        async sendIsOk() {
            // 发送修改的api

            await putAssignPrem({
                id: this.user.id,
                permIds: this.$refs.premTree.getCheckedKeys()
            })
            // 刷新路由
            await this.shuax()
            this.$message.success('更改成功')
            this.privileges = false
        },
        // 分配权限
        async btnPrivileges(id) {
            // 获取权限列表
            this.privilegesList = transListToTreeData(await getPermissionList(), 0)
            // 保存用户的id，将id用于用户的查询
            this.user = await getUserById(id)
            this.userPermIds = this.user.permIds
            this.privileges = true
        },
        // 刷新路由配置信息
        async shuax() {
            let { roles } = await store.dispatch('user/getUserInfo')
            // asyncRoutes,获取动态路由信息

            const filterRoutes = asyncRoutes.filter(item => {
                // return true/false
                return roles.menus.includes(item.name)
            })
            // 为vuex的路由信息设置
            store.commit('user/setRoutes', filterRoutes)
            // 筛选后的路由
            // 添加动态路由
            router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
        },
        async getPageList() {
            let { rows, total } = await getRoleList(this.pageList)
            this.list = rows
            this.pageList.total = total
            // 给所有的数据对象动态添加一个标记
            this.list.forEach(item => {
                this.$set(item, 'tag', false)
            })
        },
        roleBtnPage(newPage) {
            this.pageList.page = newPage
            this.getPageList()
        },
        btnOK() {
            // 表单验证
            this.$refs.roleForm.validate(async isOK => {
                if (isOK) {
                    // 发送请求
                    await setNewRole(this.formValue)
                    Message.success('新增成功！')

                    // 获取最新数据
                    this.getPageList()
                    // 关闭表单
                    this.btnCancel()
                }
            })
        },
        async btnSwitch(e, row) {
            // 调用修改
            // await this.editOK(row)
            this.$message.success('修改成功')
        },
        btnCancel() {
            // 清空表单整体方案
            this.formValue = this.$options.data().formValue
            this.$refs.roleForm.resetFields()
            // 关闭表单
            this.dialogFormVisible = false
        },
        // 修改用户
        async updataRoleList(row) {
            // 打开行内编辑的开关
            row.tag = true
            // 用id调用用户信息
            // this.formValue = await getLonely(row.id)
            // 给原先数据另存数据
            this.$set(row, 'cache', {
                name: row.name,
                state: row.state,
                description: row.description
            })
        },
        // 确认修改
        async editOK(row) {
            // 断空
            if (row.cache.name && row.cache.description) {
                // 拿缓存数据调用接口
                await updateLonely({
                    id: row.id,
                    ...row.cache
                })
                // 拿缓存数据更改原始表单
                // 浅拷贝办法
                Object.assign(row, row.cache)
                // 原始办法
                // row.name = row.cache.name
                // row.state = row.cache.state
                // row.description = row.cache.description
                this.$message.success('更新成功')
                // 关闭修改状态
                this.editCancel(row)
            } else {
                this.$message.warning('不能留空')
            }
        },
        // 取消修改
        editCancel(row) {
            row.tag = false
            row.cache = {}
        },
        async delRoleList(id) {
            await delLonely(id)
            // 判断本页数据
            // 总条数 % 每页数据 === 0
            Message.success('删除成功！')
            if (this.list.length === 1) {
                // 当前页无数据
                // 跳转到上一页
                this.pageList.page--
            }
            this.getPageList()
        }
    }
}
</script>
<style lang="scss" scoped>
.app-container {
    background-color: #fff;
}
</style>
